package mrusanov.league

import mrusanov.team.Team
import mrusanov.tournament.{RoundRobinTournamentReward, RoundRobinTournamentRound, Tournament}
import mrusanov.calendar.SeasonCalendar
object League {
  def gameDates(year:Int, clubs:Int, rounds:Int) = new SeasonCalendar(year).datesOfLeagueTournament((clubs - 1) * rounds)
}

class League(val teams:Vector[Team], name:String, system:LeagueInfoSystem, level:Int, year:Int,
             reward:RoundRobinTournamentReward = new RoundRobinTournamentReward(_ => 0))
  extends Tournament(name, Vector(new RoundRobinTournamentRound(teams.size, 1, 0, system.leagues(level).rounds,
    League.gameDates(year, teams.size, system.leagues(level).rounds),reward))){

  initTournament(teams.toList)

  def info = system.leagues(level)
  def promotedCount = info.promoted
  def promoted = rounds(0).resultsForReward.take(promotedCount)
  def relegatedCount:Int = {
    if (system.levels == level + 1) {
      0
    } else {
      val lowerLeague = system.leagues(level + 1)
      (lowerLeague.promoted * lowerLeague.leagues) / info.leagues
    }
  }
  def relegated = rounds(0).resultsForReward.reverse.take(relegatedCount)
  def notChangedLeague = teams.filterNot(relegated.contains(_)).filterNot(promoted.contains(_))
}

